from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.views import logout
from staff.models import *
from inventory.models import *
import datetime
from exchanges.models import *

showing = 0

def redirect(request, url):
    return HttpResponseRedirect(url)

def sales_home(request):
    global showing
    if showing != 0:
        request.show = showing
        showing = 0
    request.clients = Client.objects.all()
    request.currencies = Currency.objects.all()
    return render_to_response('exchanges/home.html', {'request': request, 'styles': ['exchanges_home.css'], 'scripts':['tools.js', 'ajax.js', 'exchanges_home.js', 'reports.js']})

def sales_sell(request):
    c = Client.objects.get(id=request.POST['client'])
    p = Person.objects.get(user=request.user)
    ven = Vendor.objects.get(id=p.id)
    date = datetime.datetime.now()
    cur = Currency.objects.get(id=request.POST['discount_currency'])
    dis = request.POST['discount']
    if dis == None:
        dis = 0
    if dis == '':
        dis = 0
    payment = request.POST['payment_method']
    if payment == '0':
        pay = 0
    else:
        pay = 1
    bill = request.POST['bill_number']
    cur_sale = Sale(made=date, client=c, vendor=ven, payment_method=payment, bill_number=bill, discount=dis, discount_currency=cur, payed=pay)
    cur_sale.save() 
    log = Log(id_user=request.user, action=15, id_action=cur_sale.id, datetime=datetime.datetime.now())
    log.save()
    
    if request.POST['articles_count'] != None:
        articles_count = request.POST['articles_count']
    else:
        articles_count = 0
    
    if request.POST['vinyls_count'] != None:
        vinyls_count = request.POST['vinyls_count']
    else:
        vinyls_count = 0
        
    if request.POST['wheels_count'] != None:
        wheels_count = request.POST['wheels_count']
    else:
        wheels_count = 0
        
    for i in range(int(articles_count)):
        art = Item.objects.get(id=request.POST['article_' + (u'%d' % i)])
        art.sold = True
        art.save()
        asold = ArticleSold(sale=cur_sale, item=art)
        asold.save()

    for i in range(int(vinyls_count)):
        vin = Vinyl.objects.get(id=request.POST['vinyl_' + (u'%d' % i)])
        vin.quantity = float(vin.quantity) - float(request.POST['vinyl_quantity_' + (u'%d' % i)])
        vin.save()
        vsold = VinylSold(sale=cur_sale, vinyl=vin, quantity=request.POST['vinyl_quantity_' + (u'%d' % i)])
        vsold.save()
        
    for i in range(int(wheels_count)):
        whe = Wheel.objects.get(id=request.POST['wheel_' + (u'%d' % i)])
        whe.quantity = int(whe.quantity) - int(request.POST['wheel_quantity_' + (u'%d' % i)])
        whe.save()
        c = Currency.objects.get(id=request.POST['wheel_currency_' + (u'%d' % i)])
        ws = WheelSold(sale=cur_sale, wheel=whe, trade_mark=request.POST['wheel_trade_mark_' + (u'%d' % i)], codigo=request.POST['wheel_code_' + (u'%d' % i)], price=request.POST['wheel_price_' + (u'%d' % i)], currency=c)
        ws.save()
    global showing
    showing = cur_sale.id
    return redirect(request, '/sales/')

def reports_home(request):
    return render_to_response('exchanges/reports.html', {'request': request, 'styles': ['reports.css'], 'scripts':[]})

def reports_sales(request):
    if request.method == 'POST':
        if request.POST['search_method'] == '1':
            import datetime
            start_date = datetime.date(int(request.POST['from_year']), int(request.POST['from_month']), int(request.POST['from_day']))
            end_date = datetime.date(int(request.POST['to_year']), int(request.POST['to_month']), int(request.POST['to_day']))
            request.sales = Sale.objects.filter(made__range=(start_date, end_date)).order_by('-made')
            request.message = u'Ventas desde %s-%s-%s al %s-%s-%s' % (request.POST['from_day'], request.POST['from_month'], request.POST['from_year'], request.POST['to_day'], request.POST['to_month'], request.POST['to_year'])
        if request.POST['search_method'] == '2':
            c = Client.objects.get(id=request.POST['client'])
            request.sales = Sale.objects.filter(client=c).order_by('-made')
            request.message = 'Ventas al cliente %s %s' % (c.user.first_name, c.user.last_name)
        if request.POST['search_method'] == '3':
            v = Vendor.objects.get(id=request.POST['vendor'])
            request.sales = Sale.objects.filter(vendor=v).order_by('-made')
            request.message = 'Ventas realizadas por el vendedor %s %s - [%s]' % (v.user.first_name, v.user.last_name, v.user.username)
    else:
        request.message = 'Ultimas 10 ventas'
        request.sales = Sale.objects.all().order_by('-made')[:10]
    request.clients = Client.objects.all()
    request.vendors = Vendor.objects.all()
    return render_to_response('exchanges/sales.html', {'request': request, 'styles': ['reports.css'], 'scripts':['tools.js', 'reports.js']})


def report_sale_show(request, id_sale):
    request.sale = Sale.objects.get(id=id_sale)
    request.articles = ArticleSold.objects.filter(sale=request.sale)
    request.vinyls = VinylSold.objects.filter(sale=request.sale)
    request.wheels = WheelSold.objects.filter(sale=request.sale)
    request.total = 0
    for i in request.articles:
        request.total += float(i.item.sale_price) * float(i.item.currency.multiplier)
    for i in request.vinyls:
        request.total += float(i.vinyl.price) * float(i.vinyl.currency.multiplier) * float(i.quantity)
    for i in request.wheels:
        request.total += float(i.price) * float(i.currency.multiplier)
    return render_to_response('exchanges/sale_show.html', {'request': request, 'styles': ['reports_show.css'], 'scripts':[]})

def daily_sales(request):
    if request.method != 'POST':
        request.date = datetime.datetime.now()
    else:
        request.date = datetime.datetime(int(request.POST['year']), int(request.POST['month']), int(request.POST['day']))
    first = datetime.date(request.date.year, request.date.month, request.date.day)
    secon = first + datetime.timedelta(hours=24)
    request.sales = Sale.objects.filter(made__range=(first, secon)).order_by('-made')
    request.sales_total = 0
    for s in request.sales:
        articles_sold = ArticleSold.objects.filter(sale=s)
        for i in articles_sold:
            request.sales_total += float(i.item.sale_price) * float(i.item.currency.multiplier)
        vinyl_sold = VinylSold.objects.filter(sale=s)
        for i in vinyl_sold:
            request.sales_total += float(i.vinyl.price) * float(i.vinyl.currency.multiplier) * float(i.quantity)
        wheels_sold = WheelSold.objects.filter(sale=s)
        for i in wheels_sold:
            request.sales_total += float(i.price) * float(i.currency.multiplier)
                                                                                           
    return render_to_response('exchanges/daily_sales.html', {'request':request, 'styles':['reports.css'],  'scripts':['tools.js', 'reports.js']})

